package com.niji.littly_donkey_android.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.*;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.android.volley.*;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.niji.littly_donkey_android.R;
import com.niji.littly_donkey_android.http.ConnectViaSession;
import com.niji.littly_donkey_android.util.*;
import org.json.JSONException;


import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class GetPhoneCodeActivity extends BaseActivity {
    private final static String TAG = "GetPhoneCodeActivity";

    private Button get_phone_code_return;

    private EditText get_phone_code_phone_code;

    private Button btn_get_phone_code;

    private Handler handler = new Handler();

    private Runnable runnable;

    boolean isExit;

    String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    List<String> mPermissionList = new ArrayList<>();

    // private ImageView welcomeImg = null;
    private static final int PERMISSION_REQUEST = 1;
    // 检查权限

    private void checkPermission() {
        mPermissionList.clear();

        //判断哪些权限未授予
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        /**
         * 判断是否为空
         */
        if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了

        } else {//请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(GetPhoneCodeActivity.this, permissions, PERMISSION_REQUEST);
        }
    }

    /**
     * 响应授权
     * 这里不管用户是否拒绝，都进入首页，不再重复申请权限
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST:

                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        checkPermission();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.get_phone_code_activity);
        init();
        getPhoneCodeReturn();
        getPhoneCode();
    }

    private void init() {
        Intent intent = getIntent();
        String loginCode = intent.getStringExtra("loginCode");
        if(loginCode == null){
            String sessionid = new ConnectViaSession(GetPhoneCodeActivity.this).GetSession();
            if(sessionid != null){
                startActivity(new Intent(GetPhoneCodeActivity.this,IndexActivity.class));
            }
        }else if(loginCode.equals("-1")){

        }


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    public void exit(){
        if (!isExit) {
            isExit = true;
            Toast.makeText(GetPhoneCodeActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            System.exit(0);
        }
    }


    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            isExit = false;
        }

    };

    @Override
    protected int getLayoutId() {
        return R.layout.get_phone_code_activity;

    }
    @Override
    protected int getStatusBarColor() {
        return R.color.white_easy_photos;
    }


    /**
     * 返回按钮
     */
    private void getPhoneCodeReturn() {
        get_phone_code_return = findViewById(R.id.get_phone_code_return);
        get_phone_code_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                overridePendingTransition(R.anim.xpage_slide_in_left,R.anim.xpage_slide_out_right);
                finish();
            }
        });
    }

    /**
     * 获取短信验证码
     */
    private void getPhoneCode() {

        get_phone_code_phone_code = findViewById(R.id.get_phone_code_phone_code);
        btn_get_phone_code = findViewById(R.id.btn_get_phone_code);
        get_phone_code_phone_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (runnable != null) {
                    handler.removeCallbacks(runnable);
                }
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        //结束后进行操作
                        String phone = get_phone_code_phone_code.getText().toString().trim();
                        if (!CheckUtil.isMobile(phone)) {
                            Toast.makeText(GetPhoneCodeActivity.this, "手机号格式不正确", Toast.LENGTH_SHORT).show();

                        }else {
                            btn_get_phone_code.setClickable(true);
                            btn_get_phone_code.setBackgroundColor(Color.parseColor("#4258d0"));
                        }
                    }
                };
                handler.postDelayed(runnable, 1000);
            }
        });

        get_phone_code_phone_code.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus){
                    String phone = get_phone_code_phone_code.getText().toString().trim();
                    if (!CheckUtil.isMobile(phone)) {
                        Toast.makeText(GetPhoneCodeActivity.this, "手机号格式不正确", Toast.LENGTH_SHORT).show();

                    }else {
                        btn_get_phone_code.setClickable(true);
                        btn_get_phone_code.setBackgroundColor(Color.parseColor("#4258d0"));
                        btn_get_phone_code.setTextColor(Color.parseColor("#ffffff"));
                    }

                }
            }
        });

        btn_get_phone_code.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  String phone = get_phone_code_phone_code.getText().toString().trim();
                  btn_get_phone_code.setClickable(true);
                  String url = UrlUtil.URL + "/send/code";
                  RequestQueue requestQueue = Volley.newRequestQueue(GetPhoneCodeActivity.this);
                  StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                      @Override
                      public void onResponse(String s) {
                          Log.i(TAG, s.toString());
                          try {
                              Map<String, Object> map = JsonUtil.jsonToMap(s.toString());
                             Integer data = (Integer) map.get("code");
                             if(data == 0){
                                 Intent intent = new Intent(GetPhoneCodeActivity.this,LoginActivity.class);
                                 intent.putExtra("phone",phone);
                                 startActivity(intent);
                                 finish();
                             }

                          } catch (JSONException e) {
                              e.printStackTrace();
                          } catch (Exception e) {
                              e.printStackTrace();
                          }
                          System.out.println("text");
                      }
                  }, new Response.ErrorListener() {
                      @Override
                      public void onErrorResponse(VolleyError volleyError) {

                      }
                  }){
                      @Override
                      protected Map<String, String> getParams() throws AuthFailureError {
                          Map<String, String> map = new HashMap<>();
                          map.put("phone",phone);
                          map.put("type","1");
                          return map;

                      }
                  };
                  requestQueue.add(stringRequest);


              }

            }
        );
    }

}


